<script setup lang="ts">
import {onMounted, ref} from "vue";
import {getProjects} from "../lib/api.ts";
import {openUrl} from "../lib/lib.ts";
import {GitlabOutlined,PlusCircleOutlined,HomeOutlined} from "@ant-design/icons-vue";
import {sUrl} from "../lib/lib.ts";
const open = ref<boolean>(false);
const myFav=ref([])
const projects=ref([])
const projectsOptions=ref([])

const goHome=()=>{
  window.open(sUrl(''))
}

const addFav=()=>{
  open.value=true
}
const displayProjects=ref([])
const favToDisplay=() => {
  console.log('我的项目',myFav.value)
  displayProjects.value=projects.value.filter((p: { id: any; }) => myFav.value.includes(p.id) )
  console.log('我的项目',displayProjects.value,projects.value)
}
const setFav=()=>{
 favToDisplay()
  open.value=false
  localStorage.setItem('myFavProjects',JSON.stringify(myFav.value))
  console.log(myFav.value)
  return myFav.value
}


onMounted(async ()=>{
 let projectsData=localStorage.getItem('projects')
  if(projectsData){
    projects.value=JSON.parse(projectsData)
    let favData=localStorage.getItem('myFavProjects')
    if(favData){
      myFav.value=JSON.parse(favData)
      favToDisplay()
    }
  }
  getProjects().then((data: any)=>{
    projects.value=data.map((p: any)=>{
      return p
    })
    projectsOptions.value=projects.value.map((item: any)=>{
      return {
        label:item.name_with_namespace,
        value:item.id,
      }
    })
    let favData=localStorage.getItem('myFavProjects')
    if(favData){
      myFav.value=JSON.parse(favData)
      favToDisplay()
    }
    localStorage.setItem('projects',JSON.stringify(projects.value))
  })

})
const filterOption = (input: string, option: any) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
</script>

<template>
  <a-button @click="goHome"><HomeOutlined /> 首页</a-button>
  <div style="margin-top: 15px">我关心的项目</div>
  <div style="margin-top: 10px;display: flex;gap:8px;flex-wrap: wrap" >
    <a-button @click="openUrl(p.web_url)"   v-for="p in displayProjects"><GitlabOutlined /> {{p.name}}</a-button>
    <a-button type="primary" @click="addFav"><PlusCircleOutlined /> 添加</a-button>
  </div>
  <a-modal ref="modalRef" v-model:open="open" ok-text="确定"  cancel-text="关闭" :wrap-style="{ overflow: 'hidden' }" @ok="setFav">
    <div>选择你关心的项目</div>
    <a-select :filter-option="filterOption"
        v-model:value="myFav"
        mode="multiple"
        style="width: 100%;margin-top: 10px"
        placeholder="Please select"
        :options="projectsOptions"
    ></a-select>
  </a-modal>
</template>

<style scoped lang="scss">

</style>